﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Drawing;
using System.Web.UI;
using Telerik.Web.UI;
using KPIS.Utils;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using KPIS.GERP.GHRMS.APP.Classes;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class MP_Positions : Page
    {
        private SsMng ssMng = new SsMng();
        private Main main = new Main();
        private IPositionBLL posBLL = new PositionBLL();
        private IJobSiteBLL jobsiteBLL = new JobSiteBLL();
        private IEmployeeTypeBLL emptypeBLL = new EmployeeTypeBLL();
        private IPositionTypeBLL postypeBLL = new PositionTypeBLL();
        private IFieldBLL fieldBLL = new FieldBLL();
        private IExecutiveBLL execBLL = new ExecutiveBLL();
        private IClassSpecificationBLL specBLL = new ClassSpecificationBLL();
        private PositionExtraBLL extBLL = new PositionExtraBLL();
        private JobSiteInfo jobsiteInfo = new JobSiteInfo();
        private ITreeViewBLL treeBLL = new TreeViewBLL();
		private IClassBLL classBLL = new ClassBLL();
        private int idJobSiteSeqRoot = 1; //ฝั่งโครงสร้างตามกฎกระทรวง

        protected void Page_Load(object sender, EventArgs e)
        { 
            //Nullable<int> JobSite = RadTreeView1.SelectedValue.Length <= 0 ? (int?)null : Convert.ToInt32(RadTreeView1.SelectedValue);
			 
			if (!Page.IsPostBack)
			{
				string JobSite = "";

				FillDataToEmpType();
				LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
				RadTreeNode selected_node = RadTreeView1.SelectedNode;

				OnUpdateCmdUI("");
				Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
				cmbEmpType.SelectedValue = Convert.ToString(Session["EMP_TYPE_SEQ"]);
			} 
        } 

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["update"] = Session["update"];
        }

        private void OnUpdateCmdUI(string Mode)
        {
			bool empTypeSelected = !string.IsNullOrEmpty(Convert.ToString(Session["EMP_TYPE_SEQ"]));
            bool bViewMode = Mode == "VIEW";
            bool bAddNewMode = Mode == "ADDNEW";
            bool bEditMode = Mode == "EDIT";
            bool bNull = Mode == "";


            txtSalaryQuota.ReadOnly = bEditMode;

			PanelDetail.Visible = bViewMode;
            PanelEdit.Visible = !bViewMode && !bNull;

			cmdAddNew.Visible = bNull && empTypeSelected;

            cmdDelete.Visible = bViewMode;
            cmdEdit.Visible = bViewMode;

            _btnAddnew.Visible = bAddNewMode;
			_btnUpdate.Visible = bEditMode;

			RadTreeView1.Visible = empTypeSelected;
           
            if (bViewMode)
            {
                LoadDetail();
                LoadDataGrid();
            }
            else if (bAddNewMode)
            {
                ClearControl();
            }
            else if (bEditMode)
            {
                BindDataControl();
            }

        }

        private void LoadDataGrid()
        {
            try
            {
                Nullable<int> PosSeq = string.IsNullOrEmpty(lblSequence.Text) ? (int?)null : Convert.ToInt32(lblSequence.Text.Trim());
                DataSet ds = extBLL.LoadPositionExtra((int?)null, PosSeq, (int?)null);
  
                RadGrid2.DataSource = ds.Tables[0];
                RadGrid2.DataBind();
            }
            catch (Exception ex)
            {
                Web.ShowAlert(this, ex.Message);
            }
        }

        protected void RadGrid2_ItemCommand(object source, GridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "btnClick")
                    return;

                if (e.CommandName == "Delete")
                {
                    int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["pos_ext_seq"]);
                    extBLL.Delete(seq, ssMng.EmpSeqI);
                }
                LoadDataGrid();
            }
            catch (Exception ex)
            {
                Web.ShowAlert(this, ex.Message);
            }

        }

        public void LoadDataGrid(string JobSite)
        {
            //DataSet ds = null;
            //DataTable dt = null;
            //Nullable<int> nEmployeeType = cmbEmpType.SelectedValue.Length > 0 ? Int32.Parse(cmbEmpType.SelectedValue) : (int?)null;

            //ds = posBLL.LoadPositions((int?)null, nEmployeeType, Int32.Parse(JobSite));
            //dt = ds.Tables[0].Copy();
            //RadGrid1.DataSource = dt;

            //GridGroupByExpression g = new GridGroupByExpression(RadGrid1.Columns[7]);
            //RadGrid1.MasterTableView.GroupByExpressions.Add(g);

            //RadGrid1.DataBind();
            //AddExpression();
            //RadGrid1.Rebind();
        }

        private void BindDataControl()
        {
            FillDataToEmpType();
            FillDataToExecPositions();
            FillDataToUpperPos(1);
            FillDataToJobSite();
            int Sequence = Session["TreeNodeValue"].ToString().Length > 0 ? Int32.Parse(Session["TreeNodeValue"].ToString()) : idJobSiteSeqRoot;

            DataSet ds = posBLL.LoadPositions(Sequence, (int?)null, (int?)null, "");
            DataRowCollection drc;

            if (ds.Tables.Count > 0)
            {
                drc = ds.Tables[0].Rows;
                if (drc.Count > 0)
                {

                    lblSequence.Text = drc[0]["POS_SEQ"].ToString();
                    lblPosRef.Text = drc[0]["POS_REF"].ToString();
                    cmbEmpType.SelectedValue = drc[0]["EMP_TYPE_SEQ"].ToString();
                    FillDataToPositionType(Int32.Parse(cmbEmpType.SelectedValue));

                    cmbPosType.SelectedValue = drc[0]["POS_TYPE_SEQ"].ToString();
                    FillDataToFieldPositions(cmbPosType.SelectedValue);
                    FillDataToClassSpec(cmbPosType.SelectedValue);
	                FillDataToClass(cmbPosType.SelectedValue, cmbEmpType.SelectedValue);

                    //if (DataBinder.Eval(DataItem, "Field.Sequence") != null)
                        cmbFieldPosition.SelectedValue = drc[0]["FIELD_POS_SEQ"].ToString();

                    //if (DataBinder.Eval(DataItem, "Executive.Sequence") != null)
                        cmbExecPosition.SelectedValue = drc[0]["EXEC_POS_SEQ"].ToString();

                    //if (DataBinder.Eval(DataItem, "ClassSpecification.Sequence") != null)
						// cmbClassSpec.SelectedValue = drc[0]["CLASS_SPEC_SEQ"].ToString();
						//cmbClassSpec.SelectedValue = drc[0]["class_seq"].ToString();
                        cmbClass.SelectedValue = drc[0]["class_seq"].ToString();
                        Session["CLASS_SEQ"] = drc[0]["class_seq"].ToString();
                        // Session["CLASS_SPEC"] = drc[0]["CLASS_SPEC_SEQ"].ToString();

                    //if (DataBinder.Eval(DataItem, "JobSite.Sequence") != null)
                        cmbJobSite.SelectedValue = drc[0]["JOB_SITE_SEQ"].ToString();

                    //if (DataBinder.Eval(DataItem, "Upper.Sequence") != null)
                    cmbUpperEmpPos.SelectedValue = drc[0]["upper_pos_seq"].ToString();

					//rdoStatus.SelectedValue = drc[0]["POS_STATUS"].ToString();
                    lblStatus.Text = drc[0]["POS_STATUS"].ToString();
					SetPositionStatusLabel(posBLL.LoadEmployeeOfPosition(drc[0]["POS_SEQ"].ToString()) == null);
                    txtPosRef.Text = drc[0]["POS_REF"].ToString();
                    txtPosName.Text = drc[0]["POS_NAME"].ToString();
                    txtDateDefined.SetValue(drc[0]["DATE_DEFINED"]);
                    txtSalaryQuota.Text = drc[0]["SALARY_QUOTA"].ToString();
                    txtRemarks.Text = drc[0]["REMARKS"].ToString();

                }
            }
        }

        private void ClearControl()
        {
            FillDataToJobSite();
            lblSequence.Text = "";
            //cmbEmpType.SelectedValue = "";            
            FillDataToPositionType(Int32.Parse(Session["EMP_TYPE_SEQ"].ToString()));
            cmbPosType.SelectedIndex = 0;
            FillDataToFieldPositions(cmbPosType.SelectedValue);
            FillDataToClassSpec(cmbPosType.SelectedValue);
			FillDataToClass(cmbPosType.SelectedValue, cmbEmpType.SelectedValue);
            FillDataToExecPositions(); // Add by Aek
            FillDataToUpperPos(null);// Add by Aek

            cmbFieldPosition.ClearSelection();
            cmbExecPosition.ClearSelection();
            cmbPosType.ClearSelection();
			//cmbClassSpec.SelectedValue = "";
            cmbClass.ClearSelection();
            cmbJobSite.ClearSelection();
            cmbUpperEmpPos.ClearSelection();

            // rdoStatus.SelectedIndex = 0;
            txtPosRef.Text = "";
            txtPosName.Text = "";
            txtDateDefined.SetValue("");
            txtSalaryQuota.Text = "";
            txtRemarks.Text = "";
	        lblStatus.Text = "";
            Session["CLASS_SPEC"] = "";
	        Session["CLASS_SEQ"] = "";
            
        }

        private void LoadDetail()
        {
			// Load position
            int Sequence = Session["TreeNodeValue"].ToString().Length > 0 ? Int32.Parse(Session["TreeNodeValue"].ToString()) : idJobSiteSeqRoot;
            DataSet ds = posBLL.LoadPositions(Sequence, (int?)null, (int?)null, "");
            DataRowCollection drc;

            if (ds.Tables.Count > 0)
            {
                drc = ds.Tables[0].Rows;
                if (drc.Count > 0)
                {
                    lblSequence.Text = drc[0]["POS_SEQ"].ToString();
                    lblPosTypeName.Text = drc[0]["POS_TYPE_NAME"].ToString(); 
                    //lblFieldName.Text = drc[0]["FIELD_POS_NAME"].ToString();
					lblExecName.Text = drc[0]["EXEC_POS_NAME"].ToString();
					//lblClassName.Text = drc[0]["CLASS_SPEC_NAME"].ToString();
                    lblClassName.Text = drc[0]["class_name"].ToString();
                    Session["CLASS_SEQ"] = drc[0]["class_seq"].ToString();
					//Session["CLASS_SPEC"] = drc[0]["CLASS_SPEC_SEQ"].ToString();
                    lblJobSiteName.Text = drc[0]["JOB_SITE_NAME"].ToString();
                    lblUpperName.Text = drc[0]["POS_UPPER_TEXT"].ToString();

                    lblStatusName.Text = drc[0]["POS_STATUS_NAME"].ToString();
                    lblStatusSeq.Text = drc[0]["POS_STATUS"].ToString();
					SetPositionStatusLabel(posBLL.LoadEmployeeOfPosition(drc[0]["POS_SEQ"].ToString()) == null);
                    lblPosRef.Text = drc[0]["POS_REF"].ToString();
                    lblPosName.Text = drc[0]["POS_NAME"].ToString();
                    lblDateDefined.Text = string.Format("{0:dd/MM/yyyy}", drc[0]["DATE_DEFINED"]);
                    lblSalaryQuota.Text = string.Format("{0:N2}", drc[0]["SALARY_QUOTA"]);
					lblRemarks.Text = drc[0]["REMARKS"].ToString();
                }
            }
        }

        private void AddExpression()
        {
            GridSortExpression expression = new GridSortExpression();
            expression.FieldName = "JOB_SITE_REF";
            expression.SetSortOrder("Ascending");
            RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression);
        }

        public void FillDataToEmpType()
        {
            IList<EmployeeTypeInfo> InfoList = emptypeBLL.ListEmployeeTypes(null);

            cmbEmpType.DataSource = InfoList;
            cmbEmpType.DataBind();
        }

        public void FillDataToPositionType(Nullable<int> nEmpType)
        {
            DataSet ds = postypeBLL.LoadPositionTypes((int?)null, nEmpType);
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            cmbPosType.DataSource = dt;
            cmbPosType.DataBind();
        }

        public void FillDataToFieldPositions(string PosTypeSeq)
        {
            DataSet ds = fieldBLL.LoadFields("", PosTypeSeq, cmbEmpType.SelectedValue);
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cmbFieldPosition.DataSource = dt;
                cmbFieldPosition.DataBind();
            }    

        }

        public void FillDataToExecPositions()
        {
            IList<ExecutiveInfo> InfoList = execBLL.ListExecutives(null, SystemInfo._ActiveRecordStatus);

            cmbExecPosition.DataSource = InfoList;
            cmbExecPosition.DataBind();
        }

        public void FillDataToClassSpec(string PosTypeSeq)
        {
            int posType = PosTypeSeq.Length > 0 ? Int32.Parse(PosTypeSeq) : 0;

            DataSet ds = specBLL.LoadClassSpecification((int?)null, posType);
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
				//cmbClassSpec.DataSource = dt;
				//cmbClassSpec.DataBind();
            }            
        }

		public void FillDataToClass(string pPosTypeSeq, string pEmpTypeSeq)
		{
			int? posTypeSeq = pPosTypeSeq.Length > 0 ? (int?)Int32.Parse(pPosTypeSeq) : null;
			int? empTypeSeq = pEmpTypeSeq.Length > 0 ? (int?)Int32.Parse(pEmpTypeSeq) : null;

			DataSet ds = classBLL.LoadClasses(null, posTypeSeq, empTypeSeq);
			DataTable dt = new DataTable();
			if (ds.Tables.Count > 0)
			{
				dt = ds.Tables[0];
				cmbClass.DataSource = dt;
				cmbClass.DataBind();
			}
		}

        public void FillDataToUpperPos(Nullable<int> nPosSeq)
        {
            DataSet ds = posBLL.LoadPositions(null, null, null, "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            cmbUpperEmpPos.DataSource = dt;
            cmbUpperEmpPos.DataBind();
        }

        protected void FillDataToJobSite()
        {
            JobSiteTypeInfo Info = new JobSiteTypeInfo();
            DataSet ds = jobsiteBLL.LoadJobSites("", SystemInfo._JobsiteExternal, "", "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            cmbJobSite.DataSource = dt;
            cmbJobSite.DataBind();
        }

        private void BindTree(RadTreeView treeView)
        {
            //IList<JobSiteInfo> InfoList = jobsiteBLL.LoadJobSiteTreeView(null, Convert.ToInt32(SystemInfo._JobsiteExternal));
            Nullable<int> EmpTypeSeq = cmbEmpType.SelectedValue.Length > 0 ? Int32.Parse(cmbEmpType.SelectedValue) : (int?)null;
            IList<TreeViewInfo> infoList = posBLL.LoadPositionJobsites(EmpTypeSeq, "");
            treeView.DataSource = infoList;
            treeView.DataBind();
        }

        protected void GetPosLineName()
        {
            IList<FieldInfo> Info = fieldBLL.ListFields(cmbFieldPosition.SelectedValue);
            txtPosName.Text = Info[0].LineName;
        }

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
           string JobSite = RadTreeView1.SelectedValue.Length <= 0 ? "" : RadTreeView1.SelectedValue;
            
            if (e.CommandName == "Delete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["pos_seq"]);
                posBLL.Delete(seq, ssMng.EmpSeqI);
            }
            LoadDataGrid(JobSite);
        }

        private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            //IList<TreeViewInfo> infoList = treeBLL.LoadJobSiteAreaTreeView("");

            int? EmpTypeSeq = main.ConvertNullInt(cmbEmpType.SelectedValue);

            treeView.Nodes.Clear();

            foreach (TreeViewInfo info in posBLL.LoadPositionJobsites(EmpTypeSeq, ""))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;//  info.Id.Split('-').Count() > 1 ? info.Name : String.Format("{0} : {1}", info.Id, info.Name);
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                treeView.Nodes.Add(node);
            }  
        }

        private void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            e.Node.Dispose();
            e.Node.Nodes.Clear();

            Nullable<int> EmpType = string.IsNullOrEmpty(cmbEmpType.SelectedValue) ? (int?)null : Int32.Parse(cmbEmpType.SelectedValue);

            int childNode = 0;

            foreach (TreeViewInfo info in posBLL.LoadPositionJobsites(EmpType, e.Node.Value))// treeBLL.LoadJobSiteAreaTreeView(e.Node.Value))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name; // info.Id.Split('-').Count() > 1 ? info.Name : String.Format("{0} : {1}", info.Id, info.Name);
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                childNode = info.Children_count;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }
            if (childNode > 0)
            {
                e.Node.Expanded = true;
                e.Node.ExpandMode = expandMode;
            }
        }

        public void PopulateNodeOnEditGrid(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            Nullable<int> EmpType = string.IsNullOrEmpty(cmbEmpType.SelectedValue) ? (int?)null : Int32.Parse(cmbEmpType.SelectedValue);

	        var obj = posBLL.LoadPositionJobsites(EmpType, e.Node.Value);
            foreach (TreeViewInfo info in obj)
            {
                var node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }

            e.Node.Nodes.Clear();
            e.Node.ExpandMode = expandMode;
        }

        protected void cmdSearch_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeNodeCollection nodes = this.RadTreeView1.Nodes;
            string strSearch = txtSearch.Text.TrimEnd();

            foreach (RadTreeNode n in nodes)
            {
                n.BackColor = RadTreeView1.BackColor;
                main.ClearRecursive(n, RadTreeView1.BackColor);
            }

            foreach (RadTreeNode n in nodes)
            {
                if (strSearch.Length > 0)
                {
                    if (n.Text.IndexOf(strSearch) >= 0)
                    {
                        n.BackColor = System.Drawing.Color.Yellow;
                        n.ExpandParentNodes();
                    }
                    main.FindRecursive(n, strSearch);
                }
            }
        }

        protected void cmdExpand_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeView1.ExpandAllNodes();
        }

        protected void cmdCollapse_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeView1.CollapseAllNodes();
        }

        protected void RadTreeView1_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        }

        protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            RadTreeNode selected_node = RadTreeView1.SelectedNode;
			string value = selected_node.Value.Trim();
			string name = selected_node.Text.Trim();
			string[] root_value = value.Split(new string[] {"-"}, StringSplitOptions.None);
			int nCount = root_value.Length;
			Session["TreeNodeValue"] = value;
			Session["TreeNodeSelect"] = value;
			if (!string.IsNullOrEmpty(value))
			{
				if (nCount > 1)
				{
					Session["TreeNodeValue"] = root_value[1];
					Session["POS_SEQ"] = Session["TreeNodeValue"].ToString();
					OnUpdateCmdUI("VIEW");
				}
				else
				{
					OnUpdateCmdUI("");
				}
			}
        }

        public void RefreshTreeEdit()
        {
            //RadTreeNode selected_node = RadTreeView1.SelectedNode;
            RadTreeNode selected_node = RadTreeView1.FindNodeByValue(Session["TreeNodeSelect"].ToString());

            if (selected_node == null)
            {
                selected_node = RadTreeView1.FindNodeByValue(Convert.ToString(idJobSiteSeqRoot));
            }

            RadTreeNodeEventArgs node = new RadTreeNodeEventArgs(selected_node.ParentNode);            
            RadTreeView1.CollapseAllNodes();
            PopulateNodeOnEditGrid(node, TreeNodeExpandMode.ServerSideCallBack);
            RadTreeView1.ExpandAllNodes();
            PopulateNodeOnDemand(node, TreeNodeExpandMode.ServerSideCallBack);
        } 

        public void RefreshTreeAddNew()
        {
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
            //RadTreeNode selected_node = RadTreeView1.SelectedNode;

            //if (selected_node == null)
            //{
            //    selected_node = RadTreeView1.FindNodeByValue("0");
            //}
            //RadTreeNodeEventArgs node = new RadTreeNodeEventArgs(selected_node.ParentNode);
            //RadTreeView1.CollapseAllNodes();
            //PopulateNodeOnEditGrid(node, TreeNodeExpandMode.ServerSideCallBack);
            //RadTreeView1.ExpandAllNodes();
            //PopulateNodeOnDemand(node, TreeNodeExpandMode.ServerSideCallBack);
        }

        protected void RadTreeView1_NodeDrop(object sender, RadTreeNodeDragDropEventArgs e)
        {
            //PositionInfo Info = new PositionInfo();
            //RadTreeNode selectedNode = null;
            string newFullPath = "";
            foreach (RadTreeNode nodeDrag in e.DraggedNodes)
            {
                RadTreeNode nodeDest = e.DestDragNode;

                string nodeDestValue = nodeDest.Value; //nodeValueHiddenField.Value.Trim();
                nodeDestValue = nodeDestValue == "" ? Convert.ToString(idJobSiteSeqRoot): nodeDestValue;

                string[] nodeDragValueArr = nodeDrag.Value.Split(new[] { "-" }, StringSplitOptions.None);
                int nodeDragSeq = nodeDragValueArr.Length > 1 ? Int32.Parse(nodeDragValueArr[1]) : Int32.Parse(nodeDragValueArr[0]);

                //string nodeDragParentValue = nodeDestValue.Length > 0 ? nodeDestValue : "";
                string[] nodeRootValueArr = nodeDestValue.Split(new[] { "-" }, StringSplitOptions.None);

                if (nodeRootValueArr.Length > 1)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), 
                        "onclick", "MessageAlert('ไม่สามารถแก้ไขข้อมูลได้ เนื่องจากเลือกข้อมูลไม่ถูกต้อง')", true);
                    return;
                }

                Session["TreeNodeValue"] = Convert.ToString(nodeDragSeq);
                Session["TreeNodeSelect"] = nodeDrag.Value;
                var empSeq = ssMng.EmpSeq;

                if (nodeDragValueArr.Length > 1) // Update HRM_MP_POSITIONS
                {
                    posBLL.UpdateJobSites(nodeDragSeq, nodeDestValue, ssMng.EmpSeqI);
                    newFullPath = jobsiteBLL.ListJobSiteBySequence(Convert.ToString(nodeDest.Value))[0].FullPath;
                    newFullPath += nodeDrag.Value;
                }
                else // Update HRM_MP_JOB_SITES
                {

                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                        "onclick", "MessageAlert('ไม่สามารถเคลื่อนย้ายโครงสร้างองค์กรได้')", true);
                    return;
                    
                    // Can't use below, don't accep drag node job site.
                    var jobSiteToUpdate = jobsiteBLL.ListJobSiteBySequence(Convert.ToString(nodeDragSeq))[0];
                    jobSiteToUpdate.Upper = int.Parse(nodeDestValue);
                    jobsiteBLL.Update(jobSiteToUpdate);

                    newFullPath = jobsiteBLL.ListJobSiteBySequence(Convert.ToString(nodeDragSeq))[0].FullPath; 
                }

                //RadTreeView1.SelectedNode = node.Value;
                //selectedNode = node;
            }

            OnUpdateCmdUI("VIEW");
            RefreshTreeAddNew();

            ExpandByPath(newFullPath, ref RadTreeView1); 

            // if(selectedNode != null) main.ExpandParent(ref selectedNode);
        } 

        private void ExpandByPath(string fullPath, ref RadTreeView radTreeView)
        {
            radTreeView.CollapseAllNodes();
            
            foreach(string path in  fullPath.Split('/'))
            {
                if(!String.IsNullOrEmpty(path))
                {
                    var node = RadTreeView1.FindNodeByValue(path);
                    if (node != null)
                    {
                        PopulateNodeOnDemand(new RadTreeNodeEventArgs(node), TreeNodeExpandMode.ServerSide);
                        if(node.ParentNode != null)
                            node.ParentNode.Expanded = true; 
                    }
                }
            } 
        }

        protected void cmbEmpType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            Session["EMP_TYPE_SEQ"] = cmbEmpType.SelectedValue;
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
            LoadDataGrid(RadTreeView1.SelectedValue);
			OnUpdateCmdUI("");
        }

        protected void btnAddnew_Click(object sender, EventArgs e)
        {
            //if(Session["update"].ToString() == ViewState["update"].ToString())
            //{
            //    Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
            //}
            posBLL.Insert(txtPosRef.Text.Trim()
                , txtPosName.Text.Trim()
                , null
                , txtDateDefined.GetStringValue().Length > 0 ? DateTime.Parse(txtDateDefined.GetStringValue().Trim()) : (DateTime?)null
                , null
                , Convert.IsDBNull(txtSalaryQuota.Text) ? 0 : Convert.ToDouble(txtSalaryQuota.Text)
                , null // SalaryMax
                , null // SalaryMin
                , cmbFieldPosition.SelectedValue
                , cmbExecPosition.SelectedValue
                , cmbEmpType.SelectedValue
                , cmbJobSite.SelectedValue
                , cmbPosType.SelectedValue
                , cmbUpperEmpPos.SelectedValue
                , null
                , null//cmbClassSpec.SelectedValue
				, cmbClass.SelectedValue
                , "1" // เป็น 1 หมายถึง ว่าง   rdoStatus.SelectedValue
                , txtRemarks.Text.Trim()
                , ssMng.EmpSeqI );

            OnUpdateCmdUI("");
            RefreshTreeAddNew();
			main.MessageAlert(Page, "บันทึกข้อมูลแล้ว");
			//RadTreeView1_NodeClick(null, null);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            posBLL.Update(Convert.ToInt32(lblSequence.Text)
                , txtPosRef.Text.Trim()
                , txtPosName.Text.Trim()
                , null
                , txtDateDefined.GetStringValue().Length > 0 ? DateTime.Parse(txtDateDefined.GetStringValue().Trim()) : (DateTime?)null
                , null
                , Convert.IsDBNull(txtSalaryQuota.Text) ? 0 : Convert.ToDouble(txtSalaryQuota.Text)
                , null // SalaryMax
                , null // SalaryMin
                , cmbFieldPosition.SelectedValue    // เลือกชื่อตำแหน่งในสายงาน
                , cmbExecPosition.SelectedValue // เลือกตำแหน่งทางการบริหาร
                , cmbEmpType.SelectedValue      // เลือกประเภทบุคลากร
                , cmbJobSite.SelectedValue      // เลือกสังกัด
                , cmbPosType.SelectedValue      // เลือกประเภทตำแหน่ง
                , cmbUpperEmpPos.SelectedValue  // เลือกตำแหน่งที่ขึ้นตรง
                , null
                , null// cmbClassSpec.SelectedValue
				, cmbClass.SelectedValue
                , lblStatusSeq.Text.Trim() // rdoStatus.SelectedValue
                , txtRemarks.Text.Trim()
                , ssMng.EmpSeqI);

            RefreshTreeAddNew();    //RefreshTreeEdit();
			OnUpdateCmdUI("VIEW");
			main.MessageAlert(Page, "บันทึกข้อมูลแล้ว");
			//RadTreeView1_NodeClick(null, null);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
			try
			{

				OnUpdateCmdUI("VIEW");
				Panel1.Visible = true;
				Panel2.Visible = true;
				Panel5.Visible = true;
				Panel6.Visible = true; 
				//RadTreeView1_NodeClick(null, null);
			} catch (Exception ex)
			{
				
			}

        }

        protected void cmbPosType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            FillDataToFieldPositions(cmbPosType.SelectedValue);
			FillDataToClassSpec(cmbPosType.SelectedValue);
			FillDataToClass(cmbPosType.SelectedValue, cmbEmpType.SelectedValue);
        }

        protected void cmbFieldPosition_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            GetPosLineName();
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            OnUpdateCmdUI("ADDNEW");
        }

        protected void cmdEdit_Click(object sender, EventArgs e)
        {
			try
			{
				RadGrid1.Visible = false;
				OnUpdateCmdUI("EDIT");
			} catch (Exception ex)
			{
				
			}
        }

        protected void cmdDelete_Click(object sender, EventArgs e)
        {
            posBLL.Delete(Int32.Parse(Session["TreeNodeValue"].ToString()), ssMng.EmpSeqI);
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
            OnUpdateCmdUI("");
        }

		private void SetPositionStatusLabel(bool isPositionStatusAvailable)
		{
			if(isPositionStatusAvailable)
			{
				lblStatus.Text = "ว่าง";
				lblStatus.ForeColor = Color.DarkGreen;
				lblStatusName.Text = "ว่าง";
				lblStatusName.ForeColor = Color.DarkGreen;
			} else
			{
				lblStatus.Text = "มีคนครอง";
				lblStatus.ForeColor = Color.OrangeRed;
				lblStatusName.Text = "มีคนครอง";
				lblStatusName.ForeColor = Color.OrangeRed;
			}
		}
    }
}
